<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="140px">
			<uni-forms-item name="course_id" label="课程" required>
				<uni-data-picker v-model="formData.course_id" collection="mydb-course-list"
					field="title as text, _id as value"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="title" label="课时标题" required>
				<uni-easyinput placeholder="注意标题文字颜色和背景图靠色导致看不清的问题" v-model="formData.title"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="bannerfile" label="课时视频" required>
				<uni-file-picker file-mediatype="video" return-type="array" :limit="25"
					v-model="formData.bannerfile"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="cartoonFile" label="动漫视频" required>
				<uni-file-picker file-mediatype="video" return-type="array" :limit="25"
					v-model="formData.cartoonFile"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item v-for="(item,index) in dynamicLists" :key="item.id" :label="item.label+' '+(index+1)" required
				:rules="item.rules" :name="'files[' + item.id + ']'">
				<view class="form-item">
					<uni-easyinput v-model="dynamicFormData.names[item.id]" placeholder="请输入内容标题" />
					<uni-file-picker file-mediatype="all" return-type="array"
						v-model="dynamicFormData.files[item.id]"></uni-file-picker>
					<button class="button" size="mini" type="default" @click="del(item.id)">删除</button>
				</view>
			</uni-forms-item>
			<button type="warn" size="mini" @click="add">新增课时内容</button>
			<!-- <uni-forms-item name="isInvite" label="开启邀请">
				<switch @change="binddata('isInvite', $event.detail.value)" :checked="formData.isInvite"></switch>
			</uni-forms-item> -->
			<uni-forms-item name="status" label="生效状态">
				<switch @change="binddata('status', $event.detail.value)" :checked="formData.status"></switch>
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序">
				<uni-easyinput placeholder="数字越小，排序越前" type="number" v-model="formData.sort"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="description" label="备注">
				<uni-easyinput placeholder="备注描述" v-model="formData.description" trim="both"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/mydb-course-chapter.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'mydb-course-chapter';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"course_id": "",
				"bannerfile": [],
				"cartoonFile": [],
				"title": "",
				"sort": null,
				"status": true,
				"isInvite":false,
				"description": ""
			}
			return {
				formData,
				formOptions: {},
				dynamicFormData: {		
					names: {},
					files:{}
				},
				dynamicLists: [],
				dynamicRules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '内容不能为空'
						}]
					}
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			add() {
				this.dynamicLists.push({
					label: '课程内容',
					// rules: [{
					// 	'required': true,
					// 	errorMessage: '内容必填'
					// }],
					id: Date.now()
				})
			},
			del(id) {
				let index = this.dynamicLists.findIndex(v => v.id === id)
				this.dynamicLists.splice(index, 1)
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				console.log('dynamicFormData',this.dynamicFormData)
				console.log('dynamicLists',this.dynamicLists)
				let moreContent=[]
				this.dynamicLists.forEach((item)=>{
					moreContent.push({
						name:this.dynamicFormData.names[item.id],
						file:this.dynamicFormData.files[item.id],
					})
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm({...res,moreContent})
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).get().then((res) => {
					const data = res.result.data[0]
					let names={},files={}
					if(data.moreContent){
						data.moreContent.forEach((item,index)=>{
							let id=Date.now()+index
							names[id]=item.name
							files[id]=item.file
							
							this.dynamicLists.push({
								label:'课程内容',
								id
							})
						})
						this.dynamicFormData={
							names,
							files
						}
						console.log(this.dynamicFormData,this.dynamicLists)
					}
					if (data) {
						this.formData = data

					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>